package com.cloudcross.ssp.web.settings;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.cloudcross.ssp.common.consts.MessageKeys;

/**
 * 系统语言切换
 * <p>
 * 对于的controller函数实现动态切换语言：（Spring会自动保存到上面配置的cookie。）
 * 
 * @author wuqiang.du
 */
@Controller
@RequestMapping("settings/lang")
public class LangController {
	@Autowired
	ResourceBundleMessageSource messageSource;

	@RequestMapping(value = "/{lang}", method = { RequestMethod.GET })
	public @ResponseBody String index(Model model, @PathVariable String lang,
			HttpServletRequest request, HttpServletResponse response,
			Locale locale) {
		String msg = "";
		try {
			LocaleResolver localeResolver = RequestContextUtils
					.getLocaleResolver(request);
			if (localeResolver == null) {
				throw new IllegalStateException(
						"No LocaleResolver found: not in a DispatcherServlet request?");
			}
			LocaleEditor localeEditor = new LocaleEditor();
			localeEditor.setAsText(lang);
			localeResolver.setLocale(request, response,
					(Locale) localeEditor.getValue());

			msg = messageSource.getMessage(MessageKeys.LANG_CHANGE_SUCCESS,
					null, (Locale) localeEditor.getValue());

		} catch (Exception ex) {
			msg = messageSource.getMessage(MessageKeys.LANG_CHANGE_FAIL, null,
					locale);
		}
		return msg;
	}

}
